package nil.ed.simulator.request.client;

import org.apache.commons.io.IOUtils;
import org.openjdk.nashorn.api.scripting.AbstractJSObject;
import org.openjdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.nio.charset.StandardCharsets;

/**
 * @author lidelin.
 */
public class JsFunc {
    private static final ScriptEngineManager MANAGER = new ScriptEngineManager();

    public static NashornScriptEngine JS_ENGINE;

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        AbstractJSObject jsObject = (AbstractJSObject) JS_ENGINE.eval("callback_ptui_checkVC('1', '2', '3', '4', '5', '6', '7')");
        System.out.println(jsObject.keySet());
    }

    private static void init() throws ScriptException, NoSuchMethodException {
        AbstractJSObject obj = (AbstractJSObject) JS_ENGINE.invokeFunction("init_encryption");
        AbstractJSObject e = (AbstractJSObject) JS_ENGINE.get("e");
        e.setMember("default", obj);
    }

    static {
        try {
            JS_ENGINE = (NashornScriptEngine) MANAGER.getEngineByName( "javascript");
            JS_ENGINE.eval(IOUtils.resourceToString("/script/js/encryption.js", StandardCharsets.UTF_8));
            JS_ENGINE.eval(IOUtils.resourceToString("/script/js/callback.js", StandardCharsets.UTF_8));
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
